<template>
  <div class="dashboard-container">
    <!-- 顶部打卡区域 -->
    <div class="clock-in-section">
      <el-card class="clock-card">
        <div class="clock-buttons" id="allmap">
          <el-button
            type="primary"
            size="large"
            :disabled="hasClockedIn"
            @click="handleClockIn"
            :loading="clockInLoading"
          >
            <i class="el-icon-success"></i> 上班打卡
          </el-button>
          <div class="time-display">
            <div class="current-time">{{ currentTime }}</div>
            <div class="current-date">{{ currentDate }}</div>
          </div>
          <el-button
            type="success"
            size="large"
            :disabled="hasClockedOut"
            @click="handleClockOut"
            :loading="clockOutLoading"
          >
            <i class="el-icon-success"></i> 下班打卡
          </el-button>
        </div>

      </el-card>
    </div>
    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧区域 -->
      <el-col :span="16">
        <!-- 公告通知 -->
        <el-card class="notice-board">
          <div slot="header" class="card-header">
            <span><i class="el-icon-bell"></i> 公告通知</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleViewMore()">查看更多</el-button>
          </div>
          <el-table :data="noticesList" style="width: 100%" :show-header="false">
            <el-table-column prop="noticeTitle" label="标题">
              <template slot-scope="scope">
                <el-tag size="small" :type="scope.row.type">{{ scope.row.noticeType }}</el-tag>
                <span class="notice-title">{{ scope.row.title }}</span>
                <span class="notice-date">{{ scope.row.date }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 流程进度 -->
        <el-card class="process-board">
          <div slot="header" class="card-header">
            <span><i class="el-icon-s-operation"></i> 流程进度</span>
          </div>
          <div v-if="latestTrip">
            <el-steps :active="activeStep" align-center finish-status="success">
              <el-step
                v-for="(step, index) in currentProcess"
                :key="index"
                :title="step.title"
                :description="step.date"
              >
                <template slot="description">
          <span :class="{'process-date': true, 'process-active': index < activeStep}">
            {{ step.date }}
          </span>
                </template>
              </el-step>
            </el-steps>
          </div>
          <el-empty v-else description="暂无申请记录"></el-empty>
        </el-card>

      </el-col>

      <!-- 右侧区域 -->
      <el-col :span="8">
        <!-- 工作计划 -->
        <el-card class="work-plan">
          <div slot="header" class="card-header">
            <span><i class="el-icon-date"></i> 工作计划</span>
            <!-- 修改：添加点击事件 -->
            <!--------------------------- -->
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="showPlanDialog">
              添加
            </el-button>
            <!--------------------------- -->
          </div>
          <!-- 修改：使用 sortedWorkPlans 进行排序 -->
          <!--------------------------- -->
          <el-timeline>
            <el-timeline-item
              v-for="(plan, index) in sortedWorkPlans"
              :key="index"
              :type="plan.type"
              :timestamp="plan.time">
              {{ plan.content }}
              <!--------------------------- -->
              <!----------新增：删除按钮--- -->
              <!--------------------------- -->
              <el-button
                type="danger"
                size="mini"
                style="margin-left: 10px"
                @click="deletePlan(index)"
              >
                删除
              </el-button>
              <!--------------------------- -->
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 我的便签 -->
        <el-card class="note-board">
          <div slot="header" class="card-header">
            <span><i class="el-icon-edit"></i> 我的便签</span>
            <!-- 修改：添加点击事件 -->
            <!--------------------------- -->
            <el-button
              style="float: right; padding: 3px 0"
              type="text"
              @click="showNoteDialog">
              新建
            </el-button>
            <!--------------------------- -->
          </div>
          <div class="notes-list">
            <div v-for="(note, index) in notes" :key="index" class="note-item">
              <div class="note-content">{{ note.content }}</div>
              <div class="note-time">{{ note.time }}</div>
              <!---------新增：删除按钮--- -->
              <!--------------------------- -->
              <el-button
                type="danger"
                size="mini"
                @click="deleteNote(index)">
                删除
              </el-button>
              <!--------------------------- -->
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
  title="考勤异常说明"
  :visible.sync="absentDialogVisible"
  width="40%"
  @closed="handleRemarkClose">
  <el-form>
    <el-form-item label="异常类型">
      <el-tag type="danger">缺勤</el-tag>
    </el-form-item>
    <el-form-item label="情况说明" prop="notes">
      <el-input
        v-model="form.notes"
        type="textarea"
        :rows="4"
        placeholder="请填写缺勤原因说明（至少10字）"
        maxlength="100"
        show-word-limit
      />
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="absentDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitRemark">提交说明</el-button>
  </span>
</el-dialog>



<el-dialog
  title="考勤异常说明"
  :visible.sync="earlyDialogVisible"
  width="40%"
  @closed="handleRemarkClose">
  <el-form>
    <el-form-item label="异常类型">
      <el-tag type="danger">早退</el-tag>
    </el-form-item>
    <el-form-item label="情况说明" prop="notes">
      <el-input
        v-model="form.notes"
        type="textarea"
        :rows="4"
        placeholder="请填写早退原因说明（至少10字）"
        maxlength="100"
        show-word-limit
      />
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
        <!-- 修改：关闭弹窗应使用 earlyDialogVisible -->
      <!--------------------------- -->
        <el-button @click="earlyDialogVisible = false">取 消</el-button>
       <!--------------------------- -->
        <el-button type="primary" @click="submitRemark">提交说明</el-button>
      </span>
</el-dialog>
<!---------新增：添加工作计划弹框----- -->
 <!--------------------------- -->
 <el-dialog
      title="添加工作计划"
      :visible.sync="addPlanDialogVisible"
      width="500px">
      <el-form
        :model="formPlan"
        :rules="planRules"
        ref="planForm"
        label-width="80px">
        <el-form-item label="计划内容" prop="content">
          <el-input
            v-model="formPlan.content"
            type="textarea"
            :rows="3"
            placeholder="请输入工作计划内容"
            maxlength="200"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-time-select
            v-model="formPlan.time"
            :picker-options="{
              start: '08:00',
              step: '00:15',
              end: '20:00',
              format: 'HH:mm'
            }"
            placeholder="选择时间点">
          </el-time-select>
        </el-form-item>
        <!--状态选择器 -->
        <el-form-item label="状态" prop="type">
          <el-select
            v-model="formPlan.type"
            placeholder="请选择事件状态"
            style="width: 100%"
          >
            <el-option
              v-for="option in planStatusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addPlanDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePlanSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!--------------------------- -->
    <!------------ 新增：新建便签弹框------------------- -->
    <!--------------------------- -->
    <el-dialog
      title="新建便签"
      :visible.sync="noteDialogVisible"
      width="400px"
    >
      <el-form
        :model="formNote"
        label-width="80px"
      >
        <el-form-item label="便签内容">
          <el-input
            v-model="formNote.content"
            type="textarea"
            :rows="3"
            placeholder="请输入便签内容（最多200字）"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="noteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleNoteSubmit">保存</el-button>
      </div>
    </el-dialog>
     <!--------------------------- -->
  </div>
</template>

<script>
import { checkIn, checkOut, getTodayStatus , updateAttendanceRemark, getIpLocation} from "@/api/system/record";
import {listNotice} from "@/api/system/notice";
import { selectCurrentUserBusinessTripsById } from '@/api/system/trips'


export default {
  name: 'EmployeeDashboard',
  data() {
    return {
      planStatusOptions: [
        { label: '重要', value: 'primary', color: '#409EFF' },
        { label: '普通', value: 'success', color: '#67C23A' },
        { label: '紧急', value: 'warning', color: '#E6A23C' }
      ],
            //-----------
            addPlanDialogVisible: false,
      formPlan: {
        content: '',
        time: '',
        type: 'primary' // 默认状态
      },
      planRules: {
        content: [
          { required: true, message: '请输入计划内容', trigger: 'blur' },
          { min: 5, message: '内容至少5个字符', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择时间点', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择事件状态', trigger: 'change' }
        ]
      },
      currentTime: '',
      currentDate: '',
      hasClockedIn: false,
      hasClockedOut: false,
      clockInLoading: false,
      clockOutLoading: false,
      absentDialogVisible: false, // 缺勤对话框
      earlyDialogVisible: false,  // 早退对话框
      locationInfo: null,//定位信息
      currentLocation: null,//当前定位城市
      form: {
      notes: '',
      recordId: null // 用于存储当前考勤记录ID
      },
      // 查询参数
      queryParams: {
        noticeTitle: undefined,
        createBy: undefined,
        status: undefined
      },
      noticesList: [],//存储公告列表数据
      currentProcess: [
        { title: '提交申请', date: '' },
        { title: '审核中', date: '' },
        { title: '审批结果', date: '' }
      ],
      // 新增：工作计划本地存储初始化
      //-----------
      workPlans: JSON.parse(localStorage.getItem('workPlans')) || [

        // { content: '项目周会', time: '09:30', type: 'primary' },
        // { content: '提交周报', time: '14:00', type: 'success' }
      ],
      // 新增：便签本地存储初始化
      //-----------
      notes: JSON.parse(localStorage.getItem('notes')) || [
        { content: '今日计划，计划完成任务60%', time: '2024-03-21 22:46:02' },
        { content: '记录项目进度', time: '2024-03-20 17:27:24' },
        { content: '待办事项跟进', time: '2024-03-19 10:20:31' }
      ],
            // 新增：新建便签弹框显示控制
      //-----------
      noteDialogVisible: false,
      formNote: { content: '' },
      // 出差申请表格数据
      tripsList: [],
      // 控制流程进度
      activeStep: 1,
      // 存储最新的出差申请记录
      latestTrip: null,
    }
  },
  created() {
    this.userId = this.$store.state.user.id;
    this.updateTime()
    this.timer = setInterval(this.updateTime, 1000)
    this.fetchTodayStatus()
    this.fetchLocation()
    this.getNotice()
    this.getOneBusinessTripsApply()
    console.log("当前登录的用户id为：" + this.userId);
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {

    // 新增：显示添加工作计划弹框方法
    //-----------
    showPlanDialog() {
      this.addPlanDialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.planForm) {
          this.$refs.planForm.clearValidate();
        }
      });
    },
    //-----------
    // 新增：处理添加工作计划提交方法
    //-----------
    handlePlanSubmit() {
      this.$refs.planForm.validate(valid => {
        if (!valid) return;

        const exists = this.workPlans.some(plan => plan.time === this.formPlan.time);
        if (exists) {
          this.$message.warning('该时间点已有计划');
          return;
        }

        const newPlan = {
          content: this.formPlan.content,
          time: this.formPlan.time,
          type: this.formPlan.type // 直接使用用户选择的状态
        };

        this.workPlans.unshift(newPlan);
        this.saveWorkPlansToLocalStorage();

        this.$message.success('计划添加成功');
        this.addPlanDialogVisible = false;
        this.formPlan = { content: '', time: '', type: 'primary' }; // 重置时保留默认状态
      });
    },
    //-----------
    //百度地图定位功能
    async fetchLocation() {
      this.loading = true
      try {
        const response = await getIpLocation()
        if (response.code === 200) {
          this.locationInfo = response.data;
          this.currentLocation = this.locationInfo.address;
          this.showCurrentLocation();
        } else {
          this.$modal.msgError(response.msg)
        }
      } catch (error) {
        this.$modal.msgError('获取位置失败')
      } finally {
        this.loading = false
      }
    },
    showCurrentLocation() {
      if (this.currentLocation) {
        this.$message.success("当前位置为：" + this.currentLocation);
      } else {
        this.$message.error("当前位置为null！");
      }
    },
    //查询公告
    getNotice() {
      this.loading = true;
      listNotice(this.queryParams).then(response => {
        this.noticesList = response.rows.map(item => ({
          noticeType: item.noticeType === '1' ? '通知' : '公告',
          type: item.noticeType === '1' ? 'warning' : 'success',
          title: item.noticeTitle,
          date: this.parseTime(item.createTime)
        }));
        this.loading = false;
      });
    },
    //公告栏跳转功能
    handleViewMore() {
      // 跳转到通知公告完整列表页面
      this.$router.push('/system/notice');
    },

    //查询最新的一条出差申请记录
    getOneBusinessTripsApply() {
      const currentUserId = this.userId;
      selectCurrentUserBusinessTripsById(currentUserId).then(response => {
        if (response.rows && response.rows.length > 0) {
          // 获取最新的一条记录
          this.latestTrip = response.rows[0];
          console.log("最新的出差记录：", this.latestTrip);
          this.updateProcessStatus(this.latestTrip);
        } else {
          // 没有记录时重置状态
          this.activeStep = 1;
          this.currentProcess = [
            { title: '提交申请', date: '' },
            { title: '审核中', date: '' },
            { title: '审批结果', date: '' }
          ];
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取出差记录失败：", error);
        this.loading = false;
      });
    },
    // 更新流程进度状态
    updateProcessStatus(tripData) {
      if (!tripData) return;
      console.log("当前用户最新申请记录的status为：" + tripData.status);

      // 更新时间
      this.currentProcess[0].date = this.parseTime(tripData.createdTime); // 申请时间
      this.currentProcess[1].date = '审核中';

      // 根据状态更新进度
      switch (tripData.status) {
        case 'PENDING':
          this.activeStep = 2;
          this.currentProcess[1].date = '处理中';
          this.currentProcess[2].date = '待处理';
          break;
        case 'APPROVED':
          this.activeStep = 3;
          this.currentProcess[1].date = this.parseTime(tripData.approvalTime);
          this.currentProcess[2].date = '已通过';
          break;
        case 'REJECTED':
          this.activeStep = 3;
          this.currentProcess[1].date = this.parseTime(tripData.approvalTime);
          this.currentProcess[2].date = '已驳回';
          break;
        default:
          this.activeStep = 1;
          break;
      }
    },

    updateTime() {
      const now = new Date()
      this.currentTime = now.toLocaleTimeString()
      this.currentDate = now.toLocaleDateString()
    },
    fetchTodayStatus() {
      getTodayStatus().then(response => {
        const status = response.status;
        const notes=response.notes;
        // 新增状态判断
        if (response.data && response.data.id) {
      this.form.recordId = response.data.id;  // 设置当前记录的ID
    }
        if (status === 'ABSENT'&&notes==null) {
          this.absentDialogVisible = true;
        }
        if (status === 'EARLY_LEAVE'&&notes==null) {
          this.earlyDialogVisible = true;
        }

      }).catch(() => {
        this.$message.error('获取考勤状态失败')
      })
    },
    handleClockIn() {
      this.clockInLoading = true
      checkIn().then(response => {
        this.$message.success('上班打卡成功！')
        this.hasClockedIn = true
        this.fetchTodayStatus()
      }).catch(error => {
        this.$message.error(error.message || '打卡失败')
      }).finally(() => {
        this.clockInLoading = false
      })
    },
    handleClockOut() {
      this.clockOutLoading = true
      checkOut().then(response => {
        this.$message.success('下班打卡成功！')
        this.hasClockedOut = true
        this.fetchTodayStatus()
      }).catch(error => {
        this.$message.error(error.message || '打卡失败')
      }).finally(() => {
        this.clockOutLoading = false
      })
    },
    submitRemark() {
      if (this.form.notes.length < 10) {
        this.$message.warning('说明内容至少需要10字');
        return;
      }

      updateAttendanceRemark({
        id: this.form.recordId,
        notes: this.form.notes,
        userId: this.$store.state.user.id  // 添加当前用户ID
      }).then(() => {
        this.$message.success('说明提交成功');
                // 修改：关闭两个异常说明弹框
        //-----------
        this.absentDialogVisible = false;
        this.earlyDialogVisible = false;
        //-----------
      }).catch(error => {
        this.$message.error('提交失败: ' + (error.response?.data?.msg || '未知错误'))
      })
    },
    // 关闭弹窗时重置表单
    handleRemarkClose() {
      this.form.notes = '';
      this.form.recordId = null;
    },
        // 新增：显示新建便签弹框方法
    //-----------
    showNoteDialog() {
      this.noteDialogVisible = true;
      this.formNote.content = '';
    },
    //-----------
    // 新增：处理新建便签提交方法
    //-----------
    handleNoteSubmit() {
      if (!this.formNote.content.trim()) {
        this.$message.warning('请输入便签内容');
        return;
      }
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const newNote = {
        content: this.formNote.content.trim(),
        time: `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      };
      this.notes.unshift(newNote);
      this.saveNotesToLocalStorage();
      this.noteDialogVisible = false;
      this.$message.success('便签保存成功');
    },
    //-----------
    // 新增：格式化时间方法
    //-----------
    formatTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //-----------
    // 新增：保存便签到本地存储方法
    //-----------
    saveNotesToLocalStorage() {
      try {
        localStorage.setItem('notes', JSON.stringify(this.notes));
      } catch (error) {
        console.error('本地存储失败:', error);
        this.$message.error('便签保存失败，请重试');
      }
    },
    //-----------
    // 新增：删除便签方法
    //-----------
    deleteNote(index) {
      this.$confirm('确定要删除这条便签吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.notes.splice(index, 1);
        this.saveNotesToLocalStorage();
        this.$message.success('便签删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    //-----------
    // 新增：保存工作计划到本地存储方法
    //-----------
    saveWorkPlansToLocalStorage() {
      localStorage.setItem('workPlans', JSON.stringify(this.workPlans));
    },
    //-----------
    // 新增：删除工作计划方法
    //-----------
    deletePlan(index) {
      this.$confirm('确定要删除这条计划吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.workPlans.splice(index, 1); // 删除指定索引的计划
        this.saveWorkPlansToLocalStorage(); // 更新本地存储
        this.$message.success('计划删除成功');
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    }
    //-----------
  },
  // 新增：计算属性，对工作计划进行排序
  //-----------
  computed: {
    sortedWorkPlans() {
      return this.workPlans.slice().sort((a, b) => {
        const timeA = this.parseTime(a.time);
        const timeB = this.parseTime(b.time);
        return timeA - timeB;
      });
    }
  }
  //-----------

}
</script>


<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;

  .clock-in-section {
    margin-bottom: 20px;

    .clock-card {
      .clock-buttons {
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 20px 0;

        .time-display {
          text-align: center;

          .current-time {
            font-size: 32px;
            font-weight: bold;
            color: #303133;
          }

          .current-date {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }

  .main-content {
    .notice-board,  .work-plan, .note-board {
      margin-bottom: 20px;
      // 新增：时间轴节点样式设置
      //-----------
      .el-timeline-item {
        &[vnode="primary"] .el-timeline-item__node {
          background-color: #409EFF;
        }
        &[vnode="success"] .el-timeline-item__node {
          background-color: #67C23A;
        }
        &[vnode="warning"] .el-timeline-item__node {
          background-color: #E6A23C;
        }
      }
      //-----------
    }
    .process-board {
      .process-date {
        font-size: 13px;
        color: #909399;

        &.process-active {
          color: #409EFF;
          font-weight: bold;
        }
      }

      ::v-deep .el-step__title {
        font-size: 14px;

        &.is-success {
          color: #67C23A;
        }

        &.is-process {
          color: #409EFF;
          font-weight: bold;
        }
      }
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      span {
        font-size: 16px;
        font-weight: bold;
        i {
          margin-right: 5px;
        }
      }
    }

    .notice-title {
      margin-left: 10px;
      color: #303133;
    }

    .notice-date {
      float: right;
      color: #909399;
      font-size: 13px;
    }

    .notes-list {
      .note-item {
        padding: 10px;
        border-bottom: 1px solid #EBEEF5;

        &:last-child {
          border-bottom: none;
        }

        .note-content {
          color: #303133;
          margin-bottom: 5px;
        }

        .note-time {
          font-size: 12px;
          color: #909399;
        }
        // 新增：便签删除按钮样式
        //-----------
        .el-button {
          margin-top: 5px;
        }
        //-----------
      }
    }
  }
}
</style>
